import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

export type Log = {
  CodeType: string;
  Created: string;
  Id: string;
  Message: string;
  Severity: string;
  TimeStampOffset: string;
};

export const usePostCodeLogStore = defineStore('PostCodeLog', () => {
  const allPostCodes = ref([] as Log[]);
  const setAllPostCodes = (PostCodes: Log[]) => {
    allPostCodes.value = PostCodes;
  };
  const getPostCodesLogData = async () => {
    const postCodeLogs = await (cutPostCodesLog(
      '/redfish/v1/Systems/system/LogServices/PostCodes/Entries',
    ) as unknown as Log[]);
    setAllPostCodes(postCodeLogs);
  };
  const cutPostCodesLog = async (url: string) => {
    return await api
      .get(url)
      .then(async ({ data }) => {
        let postCodeLogs = data.Members.map(
          (log: {
            Id: string;
            Severity: string;
            Message: string;
            Created: string;
            Oem: { [index: string]: any };
          }) => {
            const { Id, Severity, Created, Oem } = log;
            return {
              Id: Id,
              Severity: Severity,
              Message: Oem.Phytium.Message,
              Created: Created,
              TimeStampOffset: Oem.Phytium.TimeStampOffset,
              CodeType: Oem.Phytium.Codetype,
            };
          },
        );
        if (data['Members@odata.nextLink']) {
          postCodeLogs = [
            ...postCodeLogs,
            ...(await cutPostCodesLog(data['Members@odata.nextLink'])),
          ];
        }
        return postCodeLogs;
      })
      .catch((error) => {
        console.log('POST Codes Log Data:', error);
        throw new Error(error);
      });
  };

  const deleteAll = async (allLogs: Log[]) => {
    return await api
      .post(
        '/redfish/v1/Systems/system/LogServices/PostCodes/Actions/LogService.ClearLog',
        undefined,
        undefined,
      )
      .then(() => {
        getPostCodesLogData();
      })
      .then(() => {
        t('pagePostCodeLogs.toast.successDelete', allLogs.length);
      })
      .catch(() => {
        throw new Error(
          t('pagePostCodeLogs.toast.errorDelete', allLogs.length),
        );
      });
  };
  return {
    allPostCodes,
    setAllPostCodes,
    getPostCodesLogData,
    cutPostCodesLog,
    deleteAll,
  };
});
